package org.m2acsi.boundary;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.m2acsi.entities.Opinion;
import org.m2acsi.entities.Opinion_;
import org.m2acsi.entities.Task;
import org.m2acsi.entities.User;

@Stateless
public class OpinionEJB extends BaseEJB<Opinion> {

    @PersistenceContext(unitName = "taskManagerPU")
    EntityManager em;

    public OpinionEJB() {
        super(Opinion.class);
    }

    @Override
    public void remove(Opinion entity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public EntityManager em() {
        return em;
    }

    public boolean alreadySubmitAnOpinion(Task task, User user) {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Opinion> cQuery = cBuilder.createQuery(entityClass);
        Root<Opinion> o = cQuery.from(entityClass);
        cQuery.select(o);
        cQuery.where(cBuilder.and(
                cBuilder.equal(o.get(Opinion_.task), task),
                cBuilder.equal(o.get(Opinion_.user), user)
        ));
        List<Opinion> list = em.createQuery(cQuery).getResultList();
        return (list.size()) > 0 ? true : false;
    }

    public List<Opinion> getOpinions(Task task) {
        CriteriaBuilder cBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Opinion> cQuery = cBuilder.createQuery(entityClass);
        Root<Opinion> o = cQuery.from(entityClass);
        cQuery.select(o);
        cQuery.where(cBuilder.equal(o.get(Opinion_.task), task));
        return em.createQuery(cQuery).getResultList();
    }
}
